<?php
namespace Admin\Model;
use Think\Model;
/**
 * @todo 统计模型
 */
class StatisticsModel extends Model{

    protected $tableName = 'service_call_log';
    
    /**
     * @todo    班车统计
     * @param   int     $activity_id  活动ID
     * @remark  班车统计（/ServiceStatistics/bus）
     */
    public function busStatistics($activity_id){
        $activity_id = (int)$activity_id;
        if($activity_id == 0){
            return false;
        }
        //行为日志
        action_log('busStatistics', 'BusPointView', $activity_id, UID);
        //获取缓存
        $data = S('service_statistics_bus');
        if(isset($data[$activity_id])){
            return $data[$activity_id];
        }
        //班车统计        
        $where['status'] = 1;
        $where['activity_id'] = $activity_id;
        $field = 'bus_point_id,departure_time_id,bus_point_name,bus_point_addres,people_num';
        $list = D('BusPointView')->field($field)->where($where)->select();
        if(!$list){
            return false;
        }
        $time_array = array_merge(array_unique(array_column($list, 'departure_time_id')));
        
        $data_array = array();
        $count = count($list);
        for ($i=0;$i<$count;$i++){
            if(isset($data_array[$list[$i]['bus_point_id']][$list[$i]['departure_time_id']])){
                $data_array[$list[$i]['bus_point_id']][$list[$i]['departure_time_id']] += $list[$i]['people_num'];
            }else{
                $data_array[$list[$i]['bus_point_id']][$list[$i]['departure_time_id']] = $list[$i]['people_num'];
                $data_array[$list[$i]['bus_point_id']]['bus_point_name'] = $list[$i]['bus_point_name'];
                $data_array[$list[$i]['bus_point_id']]['bus_point_addres'] = $list[$i]['bus_point_addres'];
            }
        }
        $result = array(
            'time' => $time_array,
            'data' => $data_array
        );
        //班车统计缓存（3600s）
        S('service_statistics_bus', array($activity_id => $result), 3600);
        return $result;        
    }
    
    
    /**
     * @todo    销售网点报名
     * @remark  销售网点报名（/ServiceStatistics/pointJoin）
     */
    public function pointJoin(){

        $activity_id = (int)I('activity_id');
        $sale_point_id = (int)I('sale_point_id');
        $start_time = strtotime(I('start_time'));
        $end_time = strtotime(I('end_time'));
        if($activity_id > 0){
            $where['activity_id'] = $activity_id;
        }else{
            $this->error = '请选择活动';
            return false;
        }
        if($start_time <= $end_time && $start_time > 0){
            $where['join_time'] = array('between',array($start_time,$end_time));
        }else if($start_time > $end_time){
            $this->error = '开始时间不能大于结束时间';
            return false;
        }else{
            $this->error = '请输入开始时间与结束时间';
            return false;
        }
        if($sale_point_id > 0){
            $where['sale_point_id'] = $sale_point_id;
        }else{
            $this->error = '请选择销售网点';
            return false;
        }
        
        //获取某活动网点下的报名数据
        $where['is_false'] = 0;
        $where['is_valid'] = 0;

        //普通票数量
        $where['ticket_level'] = 0;
        $ticket_count = M('service_activity_join')->where($where)->count();
        
        //VIP数量
        $where['ticket_level'] = 1;
        $vip_count = M('service_activity_join')->where($where)->count();
        
        $result = array(
            'ticket_count' => $ticket_count,
            'vip_count' => $vip_count,
        );
        
        //行为日志
        action_log('pointJoin', 'service_activity_join', $activity_id, UID);
        return $result;
    }
    
    
    /**
     * @todo    名单报名统计
     * @remark  名单报名统计（/ServiceStatistics/listJoin）
     */
    public function listJoin(){

        $activity_id = (int)I('activity_id');
        $roll_call_id = (int)I('roll_call_id');
        if($activity_id > 0){
            $where['activity_id'] = $activity_id;
        }else{
            $this->error = '请选择活动';
            return false;
        }
        if($roll_call_id == 0){
            $this->error = '请选择名单';
            return false;
        }
        //名单下的客户列表
        $name_list = D('ServiceApi')->getServiceRollCallCustomerList($roll_call_id);
        if(!$name_list){
            $this->error = '该名单下无客户';
            return false;
        }
        
        $name_ids = array_column($name_list, 'customer_id');
        $where['customer_id'] = array('in', $name_ids);
        $where['is_false'] = 0;
        $where['is_valid'] = 0;
        
        //普通票数量
        $where['ticket_level'] = 0;
        $ticket_count = M('service_activity_join')->where($where)->count();
        
        //VIP数量
        $where['ticket_level'] = 1;
        $vip_count = M('service_activity_join')->where($where)->count();
        
        $result = array(
            'roll_call_name' => getRollName($roll_call_id),
            'ticket_count' => $ticket_count,
            'vip_count' => $vip_count,
        );
        
        //行为日志
        action_log('listJoin', 'service_activity_join', $activity_id, UID);
        return $result;
        
    }
    
    
    /**
     * @todo    绩效统计
     * @remark  员工绩效（/ServiceStatistics/personalAchieve）
     * @remark  全员绩效（/ServiceStatistics/fullAchieve）
     */
    public function fullAchieve($member_id = '', $activity_id){
        
        if($activity_id > 0){
            $where['activity_id'] = $activity_id;
        }else{
            $this->error = '请选择活动';
            return false;
        }
        if($member_id){
            $where['generalize_member_id'] = array('in', $member_id);
        }else{
            $member_list = D('ServiceApi')->getDepartmentMember(1);
            $member_array = array();
            if($member_list){
                foreach ($member_list as $key=>$val){
                    foreach ($val['_child'] as $k=>$v){
                        $member_array[] = $v['member_id'];
                    }
                }
            }
            if(count($member_array) > 0){
                $where['generalize_member_id'] = array('in', $member_array);
            }
        }
        
        
        //普通票数量
        $where['ticket_level'] = 0;
        $ticket_count = M('service_activity_join')->where($where)->count();
        
        //VIP数量
        $where['ticket_level'] = 1;
        $vip_count = M('service_activity_join')->where($where)->count();
        
        $result = array(
            'ticket_count' => $ticket_count,
            'vip_count' => $vip_count,
            'order_count' => '0'
        );
        
        //行为日志
        action_log('fullAchieve', 'service_activity_join', $activity_id, UID);
        return $result;
    }
    
    
    /**
     * @todo    客户需求统计
     * @remark  客户需求统计（/ServiceStatistics/customer）
     */
    public function demandCount(){
        
        $member_id = array_unique((array)I('member_id',''));
        $member_id = is_array($member_id) ? implode(',',$member_id) : $member_id;
        $demand_id = I('demand_content_id','');
        //装修预算
        $decoration_budget_start = I('decoration_budget_start');
        $decoration_budget_end = I('decoration_budget_end');
        //装修时间
        $decoration_time_start = strtotime(I('decoration_time_start'));
        $decoration_time_end = strtotime(I('decoration_time_end'));
        //入户时间
        $home_time_start = strtotime(I('home_time_start'));
        $home_time_end = strtotime(I('home_time_end'));
        //$demand_content_id
        $demand_content_id = array();
        if($demand_id){
            foreach ($demand_id as $key=>$val){
                foreach ($val as $k=>$v){
                    array_push($demand_content_id, $v);
                }
            }
        }
        $type = 0;
        //0:M('service_my_customer')[员工]
        //员工ID
        if($member_id){
            $where_member['member_id'] = array('in', $member_id);
        }else{
            $this->error = '请选择员工';
            return false;
        }
        $my_customer = M('service_my_customer')->where($where_member)->select();
        $customer_id = array_column($my_customer, 'customer_id');
        if(empty($customer_id)){
            $this->error = '选中员工暂无老客户';
            return false;
        }
        //员工
        $where['customer_id'] = array('in', $customer_id);
        //1:M('service_customer_demand')[装修需求+员工]
        //需求ID
        if($demand_content_id){
            $where['demand_content_id'] = array('in', $demand_content_id);
            $type = 1;
        }
        //2:M('service_customer_house')[房屋信息+员工]
        //3:D('DemandHouseView')[装修需求+房屋信息+员工]
        //装修预算
        if($decoration_budget_start <= $decoration_budget_end && $decoration_budget_end > 0){
            $where['decoration_budget'] = array('between', array($decoration_budget_start, $decoration_budget_end));
            $type = ($type == 0 || $type == 2)? 2 : 3;
        }else if($decoration_budget_start > $decoration_budget_end){
            $this->error = '装修预算范围错误';
            return false;
        }
        //装修时间
        if($decoration_time_start <= $decoration_time_end && $decoration_time_end > 0){
            $where['decoration_time'] = array('between', array($decoration_time_start, $decoration_time_end));
            $type = ($type == 0 || $type == 2)? 2 : 3;
        }else if($decoration_time_start > $decoration_time_end){
            $this->error = '装修开始时间不能大于结束时间';
            return false;
        }
        //入户时间
        if($home_time_start <= $home_time_end && $home_time_end > 0){
            $where['home_time'] = array('between', array($home_time_start, $home_time_end));
            $type = ($type == 0 || $type == 2)? 2 : 3;
        }else if($home_time_start > $home_time_end){
            $this->error = '入户时间范围错误';
            return false;
        }
        //0:M('service_my_customer')[员工]
        //1:M('service_customer_demand')[装修需求+员工]
        //2:M('service_customer_house')[房屋信息+员工]
        //3:D('DemandHouseView')[装修需求+房屋信息+员工]
        $return = 0;
        switch ($type){
            case 0:
                $return = count($customer_id);
                break;
            case 1:
                //装修+员工
                $ids = M('service_customer_demand')->field('customer_id')->where($where)->select();
                $return = ($ids)? count(array_unique(array_column($ids, 'customer_id'))) : 0 ;
                //$return = M('service_customer_demand')->distinct('customer_id')->where($where)->count();
                break;
            case 2:
                //房屋+员工
                $ids = M('service_customer_house')->field('customer_id')->where($where)->select();
                $return = ($ids)? count(array_unique(array_column($ids, 'customer_id'))) : 0 ;
                //$return = M('service_customer_house')->where($where)->count();
                break;
            case 3:
                //装修+房屋+员工
                //$ids = D('DemandHouseView')->field('customer_id')->where($where)->select();
                //$return = ($ids)? count(array_unique(array_column($ids, 'customer_id'))) : 0 ;
                //$return = D('DemandHouseView')->where($where)->count();
                $where_demand = $where_house = $where;
                unset($where_demand['decoration_budget']);
                unset($where_demand['decoration_time']);
                unset($where_demand['home_time']);
                $id_list = M('service_customer_demand')->field('customer_id')->where($where)->select();
                if($id_list){
                    unset($where_house['demand_content_id']);
                    $demand_ids = array_unique(array_column($id_list, 'customer_id'));
                    $ids = M('service_customer_house')->field('customer_id')->where(array('customer_id' => array('in', $demand_ids)))->select();
                    $return = ($ids)? count(array_unique(array_column($ids, 'customer_id'))) : 0 ;
                }
                break;
            default:
                
        }
        
        //行为日志
        action_log('demandCount', 'service_my_customer', UID, UID);
        return $return;
    }
    
    
    /**
     * @todo    个人综合统计
     * @remark  个人综合统计（/ServiceStatistics/personalCount）
     * @remark  活动数据统计（/ServiceStatistics/activity）
     */
    public function personalCount($member_id){
        
        //活动;时间区间
        $start_time = strtotime(I('start_time'));
        $end_time = strtotime(I('end_time'));
        $activity_id = (int)I('activity_id');
        //筛选条件
        if($activity_id > 0){
            $where['activity_id'] = $activity_id;
            $people_where['activity_id'] = $activity_id;
            $express_where['activity_id'] = $activity_id;
        }else{
            $this->error = '请选择活动';
            return false;
        }
        if($member_id){
            $where['generalize_member_id'] = array('in', $member_id);
            $people_where['member_id'] = array('in', $member_id);
            $express_where['member_id'] = array('in', $member_id);
        }else{
            $this->error = '请选择员工';
            return false;
        }
        if($start_time <= $end_time && $start_time > 0){
            $where['join_time'] = array('between',array($start_time,$end_time));
            $people_where['departure_time'] = array('between',array($start_time,$end_time));
            $express_where['mail_time'] = array('between',array($start_time,$end_time));
        }else if($start_time > $end_time){
            $this->error = '开始时间不能大于结束时间';
            return false;
        }else{
            $this->error = '请输入开始时间与结束时间';
            return false;
        }
        

        //报名总数=普通票+VIP
        $ticket_field = 'ticket_level,count(customer_id) as ticket_sum';
        $ticket_list = M('service_activity_join')->field($ticket_field)->where($where)->group('ticket_level')->select();
        $ticket = array_column($ticket_list, 'ticket_sum', 'ticket_level');
        
        //转化统计
        $change_where = $where;
        $change_where['ticket_level'] = 1;
        $change_where['is_change'] = 1;
        $change_count = M('service_activity_join')->where($change_where)->count();

        //A类/B类/C类客户总数
        $level_field = 'customer_level,count(customer_id) as level_sum';
        $level_where = $where;
        $level_list = M('service_activity_join')->field($level_field)->where($level_where)->group('customer_level')->select();
        $level = array_column($level_list, 'level_sum', 'customer_level');
        
        //虚报数量
        $false_where = $where;
        $false_where['is_false'] = 1;
        $false_count = M('service_activity_join')->where($false_where)->count();
        
        //乘车总人数
        $people = D('BusDepartureView')->field('sum(people_num) as people_sum')->where($people_where)->select();
        
        //Vip邮寄量
        $vip_count = M('service_express_detail')->where($express_where)->count();
        
        //拒收量
        $express_where['mail_status'] = 3;
        $refuse_count = M('service_express_detail')->where($express_where)->count();
        
        //拒收率
        $refuse_percent = round(($refuse_count/$vip_count)*100).'%';
        $result = array(
            'join_count' => ((int)$ticket[0] + (int)$ticket[1]),
            'ticket_count' => (int)$ticket[0],
            'vip_count' => (int)$ticket[1],
            'change_count' => $change_count,
            'a_count' => (int)$level[1],
            'b_count' => (int)$level[2],
            'c_count' => (int)$level[3],
            'refuse_count' => $refuse_count,
            'refuse_percent' => $refuse_percent.' | '.$refuse_count.'/'.$vip_count,
            'false_count' => $false_count,
            'people_count' => (int)$people[0]['people_sum'],
        );
        
        //行为日志
        action_log('personalCount', 'service_activity_join', UID, UID);
        return $result;
    }
    
    
    /**
     * @todo    转化统计（个人/多人）
     * @remark  个人转化统计（/ServiceStatistics/personalChange）$activity_id = 0
     * @remark  销售网点转化（/ServiceStatistics/change）                    $activity_id > 0
     */
    public function change($member_id, $activity_id = 0){
        
        //报名类型为票点1;VIP1;转化1;//'sign_channel' => 1,
        $where = array(
            'sign_channel' => 1,
            'ticket_level' => 1,
            'is_change' => 1,
        );
        //活动;时间区间
        $start_time = strtotime(I('start_time'));
        $end_time = strtotime(I('end_time'));
        if($activity_id > 0){
            $where['activity_id'] = $activity_id;
        }else{
            $this->error = '请选择活动';
            return false;
        }
        if($member_id){
            $where['generalize_member_id'] = array('in', $member_id);
        }else{
            $this->error = '请选择员工';
            return false;
        }
        if($start_time <= $end_time && $start_time > 0){
            $where['join_time'] = array('between',array($start_time,$end_time));
        }else if($start_time > $end_time){
            $this->error = '开始时间不能大于结束时间';
            return false;
        }else{
            $this->error = '请输入开始时间与结束时间';
            return false;
        }
        $change_count = M('service_activity_join')->where($where)->count();
        
        //行为日志
        action_log('change', 'service_activity_join', $activity_id, UID);
        return $change_count;
    }
    
    /**
     * @todo    通话统计（单人/多人）
     * @remark  个人通话统计（/ServiceStatistics/personalCall）
     * @remark  多人通话统计（/ServiceStatistics/call）
     * @param   int $member_id 座席ID
     */ 
    public function call($member_id){
        //活动;时间区间
        $start_time = strtotime(I('start_time'));
        $end_time = strtotime(I('end_time'));
        if($start_time <= $end_time && $start_time > 0){
            $call_where['create_time'] = array('between',array($start_time,$end_time));
        }else if($start_time > $end_time){
            $this->error = '开始时间不能大于结束时间';
            return false;
        }else{
            $this->error = '请输入开始时间与结束时间';
            return false;
        }
        if($member_id){
            $call_where['member_id'] = array('in', $member_id);
        }
        //通话次数
        $call_count = M('service_call_log')->where($call_where)->count();
        //空号
        $call_where['call_state'] = 2;
        $empty_count = M('service_call_log')->where($call_where)->count();
        //统计
        $valid_count = $call_count - $empty_count;
        $call_percent = round(($valid_count/$call_count)*100).'%';
        $return = array(
            'call_count' => $call_count,
            'valid_count' => $valid_count,
            'call_percent' => $call_percent
        );
        
        //行为日志
        action_log('call', 'service_call_log', UID, UID);
        return $return;
    }
    
    
    /**
     * @todo    订单统计脚本
     * @param   $activity_id    活动ID
     */
    public function orderStatistics($activity_id){
        
        if($activity_id == 0){
            $this->error = 'activity_id参数错误';
            return false;
        }
        //判断是否执行过当前活动的统计脚本
        $where['activity_id'] = $activity_id;
        $info = M('service_order_statistics')->field('order_statistics_id')->find();
        if($info){
            $this->error = '当前活动订单统计已结束';
            return false;
        }
        //获取所有订单（每5000条处理一次）
        $field = 'order_id,activity_id,customer_id,order_status,order_amount,order_pay_amount,order_refund_amount,order_type';
        $order_count = M('order')->where($where)->count('order_id');
        if($order_count == 0){
            $this->error = '当前活动无订单信息';
            return false;
        }
        //$order_count = 32000  //$p=6.4 //$page=7  //$remainder=2000
        $index = 5000;
        $p_num = $order_count/$index; 
        $remainder = $order_count%$index;
        $page = (is_int($p_num))? $p_num : (int)$p_num + 1 ;
        for ($i=0;$i<$page;$i++){
            //设定5000条一循环
            $start = $i*$index;
            $limit = ($i == ($page - 1))? $remainder : $index ;
            //获取订单
            $order_list = M('order')->field($field)->where($where)->limit($start, $limit)->select();
            //获取用户ID
            $customer_ids = ($order_list)? array_column($order_list, customer_id) : array() ;
            //活动用户的推广人ID
            $where_join['customer_id'] = array('in', $customer_ids);
            $field_join = 'customer_id,generalize_member_id,ticket_level';
            $member_list = M('service_activity_join')->field($field_join)->where($where_join)->select();
            $member_id = $ticket_level = array();
            if($member_list){
                $member_id = array_column($member_list, 'generalize_member_id', 'customer_id');
                $ticket_level = array_column($member_list, 'ticket_level', 'customer_id');
            }
            //组合数据写入订单统计表
            $data = array();
            foreach ($order_list as $key=>$val){
                $data[$key] = $val;
                $data[$key]['member_id'] = (int)$member_id[$val['customer_id']];
                $data[$key]['ticket_level'] = (int)$ticket_level[$val['customer_id']];
            }
            $obj = M('service_order_statistics');
            $result = $obj->addAll($data);
            if($result == false){
                $this->error = $obj->getError();
                return false;
            }
            sleep(100);//休息休息
        }
        return true;
        /* 
        //$order_list = M('order')->field($field)->where($where)->select();
        //用户ID
        $customer_ids = array_column($order_list, customer_id);
        //活动用户的推广人ID
        $where_join['customer_id'] = array('in', $customer_ids);
        $field_join = 'customer_id,generalize_member_id,ticket_level';
        $member_list = M('service_activity_join')->field($field_join)->where($where_join)->select();
        $member_id = array_column($member_list, 'generalize_member_id', 'customer_id');
        $ticket_level = array_column($member_list, 'ticket_level', 'customer_id');
        //组合数据写入订单统计表
        $data = array();
        foreach ($order_list as $key=>$val){
            $data[$key] = $val;
            $data[$key]['member_id'] = (int)$member_id[$val['customer_id']];
            $data[$key]['ticket_level'] = (int)$ticket_level[$val['customer_id']];
        }
        $obj = M('service_order_statistics');
        $result = $obj->addAll($data);
        if($result == false){
            $this->error = $obj->getError();
            return false;
        } 
        */
    }
    
}